package com.runshu.newsmartark.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.naz.serial.port.ModuleManager;
import com.naz.serial.port.SerialPort;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.base.BaseActivity;
import com.runshu.newsmartark.base.MyApplication;
import com.runshu.newsmartark.common.ConstantUrl;
import com.runshu.newsmartark.entity.UserInfoEntity;
import com.runshu.newsmartark.event.Event;
import com.runshu.newsmartark.event.EventBusUtils;
import com.runshu.newsmartark.event.EventCode;
import com.runshu.newsmartark.mvp.contract.ReadCardContract;
import com.runshu.newsmartark.mvp.model.ReadCardModel;
import com.runshu.newsmartark.mvp.presenter.ReadCardPresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.reader.base.ReaderBase;
import com.runshu.newsmartark.reader.helper.ReaderHelper;
import com.runshu.newsmartark.reader.helper.ReaderSetting;
import com.runshu.newsmartark.util.LodDialogClass;
import com.runshu.newsmartark.util.SoundPoolUtils;
import com.runshu.newsmartark.util.ToolScanner;
import com.runshu.newsmartark.util.UserCardUtil;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.widget.TopTitleBar;

import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Demo class
 *
 * @author yu
 * @date 2020/11/1
 * @decs：
 */

public class ReaderCardAuthActivity extends BaseActivity implements ToolScanner.OnScanSuccessListener, ReadCardContract.View {
    @BindView(R.id.toolbar)
    TopTitleBar mToolbar;
    @BindView(R.id.img_readerCard)
    ImageView mImgReaderCard;
    @BindView(R.id.tv_hint)
    TextView mTvHint;
    private ToolScanner toolScanner;
    private ReaderHelper mReaderHelper;
    private static ReaderSetting m_curReaderSetting;
    private ReadCardPresenter readCardPresenter;
    private CountDownTimer timerDialog;
    private ReaderBase readerBase;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_reader_card_auth;
    }

    @Override
    protected void initView() {
        mToolbar.setTitle("刷卡登录");
        mToolbar.setIsShowBac(true);
        toolScanner = new ToolScanner(this);
        readCardPresenter = new ReadCardPresenter(this,new ReadCardModel());
        SoundPoolUtils.play(context,R.raw.raw_shuaka,0);
    }



    @Override
    protected void onResume() {
        if (readerBase != null) {
            if (!readerBase.IsAlive())
                readerBase.StartWait();
        }
        super.onResume();
    };
    @Override
    protected void initData() {
        try {
            mReaderHelper = ReaderHelper.getDefaultHelper();
            readerBase = mReaderHelper.getReader();
            m_curReaderSetting = mReaderHelper.getCurReaderSetting();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void bindListener() {

    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {

    }


    @Override
    public void onScanSuccess(String barcode) {
        String s = UserCardUtil.decimal2Hex(barcode);
        LogUtil.e("卡号：", barcode+" 转换后==="+s );
        //验证成功
        LodDialogClass.showCustomCircleProgressDialog(context);
        readCardPresenter.verifyIcCard(barcode);
    }

    @Override
    public void verifyIcCardSuccess(ResponseBean responseBean) {
        UserInfoEntity userInfoEntity = (UserInfoEntity) responseBean.pullData();
        MyApplication.application.setUserInfoEntity(userInfoEntity);
        loginSuccess();
        if (isAdmin()) {
            if (userInfoEntity.isAdmin()) {
                Intent intent = new Intent(context, ManagerActivity.class);
                startActivity(intent);
                finish();
            } else {
                Intent intent = new Intent(context, MainActivity.class);
                startActivity(intent);
                //发通知
                EventBusUtils.sendEvent(new Event(EventCode.EventNOTADMIN));
            }

        } else {
            connect();
        }
    }

    @Override
    public void onError(String msg) {
        LodDialogClass.closeCustomCircleProgressDialog();
        mTvHint.setText("身份验证失败,请重新刷卡!");
        mTvHint.setTextColor(context.getResources().getColor(R.color.color_FF3535));
        countDownShowDia();
    }

    private void connect() {
        //开灯
        readerBase.writeGpioValue(m_curReaderSetting.btReadId, (byte) 0x04, (byte) 0x01);
        //开门
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                readerBase.writeGpioValue(m_curReaderSetting.btReadId, (byte) 0x03, (byte) 0x01);
                Intent intent = new Intent(context, TakeStockDtaActivity.class);
                startActivityForResult(intent, 101);
            }
        }, 100);
    }



    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            toolScanner.analysisKeyEvent(event);
            return true;
        }
        return super.dispatchKeyEvent(event);

    }
    /**
     * 倒计时显示Dialog
     */
    private void countDownShowDia() {
        if (timerDialog != null) {
            timerDialog.cancel();
        }
        timerDialog = new CountDownTimer(1500, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                mTvHint.setText("请把您的卡片放在刷卡读卡区");
                mTvHint.setTextColor(context.getResources().getColor(R.color.color_999999));
                timerDialog.cancel();
            }
        }.start();
    }
    @Override
    protected void onDestroy() {
        if (timerDialog != null) {
            timerDialog.cancel();
        }
        super.onDestroy();
    }
}